package smstpl

import (
	"context"
	"gitee.com/bobo-rs/idea-space-framework/enums"
	"gitee.com/bobo-rs/idea-space-framework/framework/model"
	"gitee.com/bobo-rs/idea-space-framework/pkg/core/services/sms"
	"gitee.com/bobo-rs/idea-space-framework/pkg/utils"
	"strconv"
)

// SendCaptcha 发送短信验证码
func (t *sSmsTpl) SendCaptcha(ctx context.Context, mobile string, varAlias enums.SmsAlias) error {
	// 实例短信服务
	smsHandler := sms.New().Ctx(ctx)
	// 验证验证码发送安全阀规则
	if err := smsHandler.CaptchaValidate(ctx, mobile); err != nil {
		return err
	}

	// 获取6位随机数
	code := strconv.Itoa(utils.RandInt(6))

	// 调用服务-发送短信
	err := t.SendSmsOutFrom(ctx, model.SendOutFromSmsItem{
		Mobile: []string{mobile},
		SendSmsTemplateItem: model.SendSmsTemplateItem{
			TemplateParams: []string{code},
			SmsType:        enums.SmsTypeCaptcha,
			VarAlias:       varAlias,
			Code:           code,
		},
	})
	if err != nil {
		return err
	}

	// 设置验证码Code缓存
	if err = smsHandler.SetCaptchaCode(ctx, code, mobile); err != nil {
		return err
	}
	// 设置验证码安全规则
	smsHandler.AfterCaptchaSendAsync(ctx, mobile)
	return nil
}

// ValidateCode 短信验证码检验
func (t *sSmsTpl) ValidateCode(ctx context.Context, mobile, code string) error {
	return sms.New().Ctx(ctx).ValidateCode(ctx, mobile, code)
}

// SendSmsMessage 短信发送-消息通知
func (t *sSmsTpl) SendSmsMessage(ctx context.Context, item model.SendSmsTemplateItem, mobile ...string) error {
	// 发送短信-消息通知
	item.SmsType = enums.SmsTypeMessage
	return t.SendSmsOutFrom(ctx, model.SendOutFromSmsItem{
		Mobile:              mobile,
		SendSmsTemplateItem: item,
	})
}

// SendSmsMarket 短信发送-营销短信
func (t *sSmsTpl) SendSmsMarket(ctx context.Context, item model.SendSmsTemplateItem, mobile ...string) error {
	// 发送短信-营销短信
	item.SmsType = enums.SmsTypeMarket
	return t.SendSmsOutFrom(ctx, model.SendOutFromSmsItem{
		Mobile:              mobile,
		SendSmsTemplateItem: item,
	})
}
